package com.campus.manage.service.impl;

import com.campus.manage.service.IAliyunOpenAIService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliyunOpenAIServiceImpl implements IAliyunOpenAIService {

    @Value("${aliyun.dashscope.api-key:}")
    private String apiKey;

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String generateSummary(String title, String content) {
        if (apiKey == null || apiKey.isEmpty()) {
            throw new RuntimeException("阿里云API Key未配置，请在application.yml中配置aliyun.dashscope.api-key");
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost httpPost = new HttpPost(API_URL);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 构建提示词
            String prompt = buildSummaryPrompt(title, content);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-turbo");

            Map<String, String> input = new HashMap<>();
            input.put("prompt", prompt);
            requestBody.put("input", input);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("result_format", "message");
            parameters.put("max_tokens", 500);
            requestBody.put("parameters", parameters);

            String requestBodyJson = objectMapper.writeValueAsString(requestBody);
            httpPost.setEntity(new StringEntity(requestBodyJson, StandardCharsets.UTF_8));

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());

            if (statusCode != 200) {
                throw new RuntimeException("API请求失败，状态码: " + statusCode + ", 响应: " + responseBody);
            }

            // 解析响应
            return parseAPIResponse(responseBody);

        } catch (Exception e) {
            throw new RuntimeException("调用阿里云API失败: " + e.getMessage(), e);
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                // 忽略关闭异常
            }
        }
    }

    /**
     * 构建摘要提示词
     */
    private String buildSummaryPrompt(String title, String content) {
        return String.format(
                "你是一个专业的新闻编辑，请将以下新闻内容总结为一段简洁的摘要（100-150字）。\n" +
                        "要求：\n" +
                        "1. 突出核心信息，保持客观准确\n" +
                        "2. 语言简洁明了，逻辑清晰\n" +
                        "3. 使用中文回复\n\n" +
                        "新闻标题：《%s》\n" +
                        "新闻内容：%s\n\n" +
                        "请直接返回摘要内容，不需要其他说明：",
                title, content
        );
    }

    /**
     * 解析API响应
     */
    private String parseAPIResponse(String responseBody) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);

            // 检查错误
            if (rootNode.has("code")) {
                String errorMsg = rootNode.has("message") ? rootNode.get("message").asText() : "未知错误";
                throw new RuntimeException("API返回错误: " + errorMsg);
            }

            // 解析输出内容
            if (rootNode.has("output")) {
                JsonNode output = rootNode.get("output");
                if (output.has("text")) {
                    return output.get("text").asText().trim();
                } else if (output.has("choices") && output.get("choices").isArray() &&
                        output.get("choices").size() > 0) {
                    JsonNode choice = output.get("choices").get(0);
                    if (choice.has("message") && choice.get("message").has("content")) {
                        return choice.get("message").get("content").asText().trim();
                    }
                }
            }

            throw new RuntimeException("无法解析API响应格式: " + responseBody);

        } catch (Exception e) {
            throw new RuntimeException("解析API响应失败: " + e.getMessage() + ", 响应体: " + responseBody, e);
        }
    }
}